package javabase.classloader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MyClassLoader extends ClassLoader {

	
	public static void cypher(InputStream is, OutputStream os) throws IOException {
		int b = -1;
		while ((b=is.read()) != -1) {
			os.write(b ^ 0xff);
		}
	}
	
	
	public static void main(String[] args) throws FileNotFoundException, IOException {
		String srcPath = "G:\\eclipse-workspace\\4test\\target\\classes\\javabase\\reflect\\Bean.class";

		String destDir = ".";
		
		String destFileName =  srcPath.substring(srcPath.lastIndexOf("\\") + 1);
		
		String destPath = destDir + "\\" + destFileName;
		
		try(FileInputStream fis = new FileInputStream(srcPath);
				FileOutputStream fos = new FileOutputStream(destPath)) {
			cypher(fis, fos);
		}
	}
	
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String classFileName = classPath + "\\" + name + ".class";
		
		System.out.println(classFileName);
		
		try(FileInputStream fis = new FileInputStream(classFileName);
				ByteArrayOutputStream baos = new ByteArrayOutputStream()){
			cypher(fis, baos);
			byte[] bytes = baos.toByteArray();
			return defineClass(bytes, 0, bytes.length);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return super.findClass(name);
	}
	
	private String classPath;

	public MyClassLoader(String classPath) {
		super();
		this.classPath = classPath;
	}


	public MyClassLoader() {
		super();
	}
	
}
